using UnityEngine;
using UI.BankingPanel.Data;

/// <summary>
/// 银行数据管理器
/// 负责管理BankingData的生命周期、自动保存等功能
/// </summary>
public class BankingDataManager : MonoBehaviour
{
    [Header("自动保存设置")]
    [SerializeField] private bool enableAutoSave = true;
    [SerializeField] private float autoSaveDelay = 2f; // 输入后延迟保存时间（秒）
    [SerializeField] private float periodicSaveInterval = 30f; // 定期保存间隔（秒）
    
    [Header("调试信息")]
    [SerializeField] private bool showDebugInfo = true;
    
    // 单例模式
    public static BankingDataManager Instance { get; private set; }
    
    // 银行数据
    private BankingData _bankingData;
    public BankingData BankingData 
    { 
        get 
        { 
            if (_bankingData == null)
            {
                LoadBankingData();
            }
            return _bankingData; 
        } 
    }
    
    // 定期保存计时器
    private float _lastPeriodicSaveTime;
    
    void Awake()
    {
        // 确保只有一个实例
        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject);
            InitializeManager();
        }
        else
        {
            Destroy(gameObject);
        }
    }
    
    /// <summary>
    /// 初始化管理器
    /// </summary>
    private void InitializeManager()
    {
        // 设置协程运行器
        BankingDataPersistence.SetCoroutineRunner(this);
        
        // 加载银行数据
        LoadBankingData();
        
        // 初始化定期保存计时器
        _lastPeriodicSaveTime = Time.time;
        
        if (showDebugInfo)
        {
            Debug.Log("[BankingDataManager] 银行数据管理器初始化完成");
        }
    }
    
    void Update()
    {
        // 定期保存功能
        if (enableAutoSave && Time.time - _lastPeriodicSaveTime >= periodicSaveInterval)
        {
            SaveBankingData();
            _lastPeriodicSaveTime = Time.time;
            
            if (showDebugInfo)
            {
                Debug.Log("[BankingDataManager] 定期保存银行数据");
            }
        }
    }
    
    /// <summary>
    /// 加载银行数据
    /// </summary>
    public void LoadBankingData()
    {
        _bankingData = BankingDataPersistence.LoadBankingData();
        
        if (showDebugInfo)
        {
            Debug.Log("[BankingDataManager] 银行数据已加载");
            LogBankingDataSummary();
        }
    }
    
    /// <summary>
    /// 保存银行数据
    /// </summary>
    public void SaveBankingData()
    {
        if (_bankingData != null)
        {
            BankingDataPersistence.SaveBankingData(_bankingData);
            
            if (showDebugInfo)
            {
                Debug.Log("[BankingDataManager] 银行数据已手动保存");
            }
        }
    }
    
    /// <summary>
    /// 自动保存银行数据（带延迟）
    /// 适用于输入框数据变化时调用
    /// </summary>
    public void AutoSaveBankingData()
    {
        if (enableAutoSave && _bankingData != null)
        {
            BankingDataPersistence.AutoSaveBankingData(_bankingData, autoSaveDelay);
            
            if (showDebugInfo)
            {
                Debug.Log($"[BankingDataManager] 触发自动保存，延迟{autoSaveDelay}秒");
            }
        }
    }
    
    /// <summary>
    /// 更新号码押注数据并自动保存
    /// </summary>
    /// <param name="number">号码</param>
    /// <param name="totalBet">总押注</param>
    /// <param name="selfBet">自己吃码</param>
    public void UpdateNumberBetAndSave(int number, float totalBet, float selfBet)
    {
        if (_bankingData != null)
        {
            _bankingData.UpdateNumberBet(number, totalBet, selfBet);
            AutoSaveBankingData();
            
            if (showDebugInfo)
            {
                Debug.Log($"[BankingDataManager] 更新号码{number}数据: 总押注={totalBet}, 吃码={selfBet}");
            }
        }
    }
    
    /// <summary>
    /// 更新基础设置并自动保存
    /// </summary>
    /// <param name="averageBetAmount">平均吃码数</param>
    /// <param name="maxLossLimit">最大亏损限制</param>
    /// <param name="odds">赔率</param>
    public void UpdateSettingsAndSave(float? averageBetAmount = null, float? maxLossLimit = null, float? odds = null)
    {
        if (_bankingData != null)
        {
            bool hasChanges = false;
            
            if (averageBetAmount.HasValue && _bankingData.averageBetAmount != averageBetAmount.Value)
            {
                _bankingData.averageBetAmount = averageBetAmount.Value;
                hasChanges = true;
            }
            
            if (maxLossLimit.HasValue && _bankingData.maxLossLimit != maxLossLimit.Value)
            {
                _bankingData.maxLossLimit = maxLossLimit.Value;
                hasChanges = true;
            }
            
            if (odds.HasValue && _bankingData.odds != odds.Value)
            {
                _bankingData.odds = odds.Value;
                hasChanges = true;
                // 赔率变化需要重新计算风险值
                _bankingData.RecalculateAllRiskValues();
            }
            
            if (hasChanges)
            {
                AutoSaveBankingData();
                
                if (showDebugInfo)
                {
                    Debug.Log("[BankingDataManager] 基础设置已更新并触发自动保存");
                }
            }
        }
    }
    
    /// <summary>
    /// 重置所有数据
    /// </summary>
    public void ResetAllData()
    {
        if (_bankingData != null)
        {
            _bankingData.ResetAllData();
            SaveBankingData(); // 立即保存重置后的数据
            
            if (showDebugInfo)
            {
                Debug.Log("[BankingDataManager] 所有数据已重置");
            }
        }
    }
    
    /// <summary>
    /// 删除保存的数据文件
    /// </summary>
    public void DeleteSavedData()
    {
        BankingDataPersistence.DeleteBankingData();
        LoadBankingData(); // 重新加载默认数据
        
        if (showDebugInfo)
        {
            Debug.Log("[BankingDataManager] 保存数据已删除，重新加载默认数据");
        }
    }
    
    /// <summary>
    /// 检查是否有保存的数据
    /// </summary>
    /// <returns>如果有保存数据返回true</returns>
    public bool HasSavedData()
    {
        return BankingDataPersistence.HasSavedBankingData();
    }
    
    /// <summary>
    /// 获取保存文件路径
    /// </summary>
    /// <returns>保存文件路径</returns>
    public string GetSavePath()
    {
        return BankingDataPersistence.GetSavePath();
    }
    
    /// <summary>
    /// 设置自动保存功能
    /// </summary>
    /// <param name="enabled">是否启用</param>
    /// <param name="delay">延迟时间</param>
    /// <param name="periodicInterval">定期保存间隔</param>
    public void SetAutoSave(bool enabled, float delay = 2f, float periodicInterval = 30f)
    {
        enableAutoSave = enabled;
        autoSaveDelay = delay;
        periodicSaveInterval = periodicInterval;
        
        if (enabled)
        {
            _lastPeriodicSaveTime = Time.time;
        }
        
        if (showDebugInfo)
        {
            Debug.Log($"[BankingDataManager] 自动保存设置: 启用={enabled}, 延迟={delay}秒, 定期间隔={periodicInterval}秒");
        }
    }
    
    /// <summary>
    /// 输出银行数据摘要（调试用）
    /// </summary>
    [ContextMenu("显示银行数据摘要")]
    public void LogBankingDataSummary()
    {
        if (_bankingData != null)
        {
            var stats = _bankingData.GetStatisticsData();
            Debug.Log("=== 银行数据摘要 ===");
            Debug.Log($"平均吃码数: {_bankingData.averageBetAmount}");
            Debug.Log($"最大亏损限制: {_bankingData.maxLossLimit}");
            Debug.Log($"赔率: {_bankingData.odds}");
            Debug.Log($"下注总数: {stats.revenueTotal}");
            Debug.Log($"吃码总数: {stats.eatCodeTotal}");
            Debug.Log($"上报总数: {stats.reportTotal}");
            Debug.Log($"保存文件路径: {GetSavePath()}");
            Debug.Log($"是否有保存数据: {HasSavedData()}");
        }
    }
    
    /// <summary>
    /// 程序退出时保存数据
    /// </summary>
    void OnApplicationPause(bool pauseStatus)
    {
        if (pauseStatus)
        {
            SaveBankingData();
        }
    }
    
    /// <summary>
    /// 程序失去焦点时保存数据
    /// </summary>
    void OnApplicationFocus(bool hasFocus)
    {
        if (!hasFocus)
        {
            SaveBankingData();
        }
    }
    
    /// <summary>
    /// 程序退出时保存数据
    /// </summary>
    void OnApplicationQuit()
    {
        SaveBankingData();
        
        if (showDebugInfo)
        {
            Debug.Log("[BankingDataManager] 程序退出，银行数据已保存");
        }
    }
} 